package dk.controlme.lego.client;

import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import lejos.robotics.subsumption.Arbitrator;
import lejos.robotics.subsumption.Behavior;
import lejos.nxt.Button;


/**
 * Class to start Lego NXT Client.
 *
 * Assumes the following about the client:
 * - Has larvae feet.
 * - Motors are x cm apart.
 * - Motors used are A & C
 *
 * Lego NXT Client is autonomous, but under control of a BT device.
 *
 * Client LCD interface has reserved lines:
 * Line 1: CONNECTION STATUS
 * Line 2: COMMAND BEING EXECUTED
 * Line 3: Blank!
 * Line 4-7: Free to use
 * Line 8: ControlMe.dk
 */

public class LegoClient {
    static BTConnection btConnection;
    static BluetoothConnection bluetoothConnection;

    public static void main(String args[]) {
        startClient();
    }

    public static void startClient() {
        LCD.drawString("Waiting for connection", 0, 0);
        LCD.drawString("> ControlMe.dk", 0, 7);
        LCD.refresh();

        btConnection = Bluetooth.waitForConnection();
        btConnection.setIOMode(0); // Used for PC connections

        bluetoothConnection = new BluetoothConnection(btConnection);
        bluetoothConnection.start();

        LCD.clear();
        LCD.drawString("Connection established", 0, 0);
        LCD.refresh();

        try {
            // Do nothing.
        } catch(Exception e) {
            LCD.clear();
            LCD.drawString("Can not open I/O stream", 0, 0);
            LCD.refresh();
        }

        // Setup behaviours
        Behavior behavior1 = new DoMove(bluetoothConnection); // Low priority
        Behavior behavior2 = new DoExit(); // High priority
        Behavior[] behaviors = {behavior1, behavior2};
        Arbitrator arbitrator = new Arbitrator(behaviors);
        arbitrator.start();
    }

}

class DoExit implements Behavior {
    // Exit through button on client.
    public boolean takeControl() {
        return Button.ESCAPE.isPressed();
    }

    public void suppress() {
        // We don't assume any code is running, so nothing to suppress
    }

    public void action() {
        System.exit(0);
    }
}